<template>
    <div class="body">
        <div class="pageClose">
            <div class="pageTitle">更换商品</div>
            <div @click="router.back()">关闭</div>
        </div>
        <div class="boxContent">
            <div class="boxLeft">
                <div class="orderBox">
                    <div class="tableTop">
                        <div style="font-size: 20px; font-weight: bold;">桌台：{{ OrderDetail.roomName }}</div>
                        <div>需补差额：<span style="color: #FF3333;">¥ {{ formatDecimal(goodsTotalData.totlePrice) }}</span>
                        </div>
                    </div>
                    <div class="orderDetails">
                        <div class="goodsTop">
                            <div style="width: 40%; text-align: left;">商品名称</div>
                            <div style="width: 15%;">数量</div>
                            <div style="width: 15%;">单价</div>
                            <div style="width: 20%;">收款金额</div>
                            <div style="width: 10%;">操作</div>
                        </div>
                        <div class="goodsList">
                            <div class="goodsItem" v-for="(item, index) in OrderDetail.consumeList" :key="index">
                                <div style="width: 40%; text-align: left;">{{ item.goodsName }}</div>
                                <div style="width: 15%;">{{ item.goodsQty }}</div>
                                <div style="width: 15%;" v-if="!item.isUseVipPay">{{ formatDecimal(item.salePrice) }}</div>
                                <div style="width: 15%;" v-if="item.isUseVipPay">{{ formatDecimal(item.vipPrice) }}</div>
                                <div style="width: 20%;">{{ formatDecimal(item.payAmt) }}</div>
                                <div style="width: 10%; color: #00AAFF; cursor: pointer;"
                                    @click="replaceDishes(item, index)">换菜</div>
                            </div>
                        </div>
                        <div class="totalAmt">已点商品：¥ {{ OrderDetail.totalAmt }}</div>
                    </div>
                    <div class="orderDetails">
                        <div class="goodsTop">
                            <div style="width: 50%; text-align: left;">商品名称</div>
                            <div style="width: 15%;">数量</div>
                            <div style="width: 15%;">单价</div>
                            <div style="width: 20%;">金额</div>
                        </div>
                        <div class="goodsList">
                            <div class="goodsItem" v-for="(item, index) in menuGoodsList" :key="index"
                                :class="{ MenuItemActive: index == isMenuItemActive, isNew: item.isNew == '0' }"
                                @click="editItem(item, index)">
                                <div style="width: 50%; text-align: left;">{{ item.goodsName }}</div>
                                <div style="width: 15%;" class="spe">{{ item.flavor }}</div>
                                <div style="width: 15%;"><span v-if="item.isNew == '0'">-</span>{{ item.goodsQty }}</div>
                                <div style="width: 15%;" v-if="!isVipPay">{{ formatDecimal(item.salePrice) }}</div>
                                <div style="width: 15%;" v-if="isVipPay">{{ formatDecimal(item.vipPrice)}}</div>
                                <div style="width: 20%;">
                                    <span v-if="item.isNew == '0'">-</span>
                                    {{ isVipPay ? formatDecimal(item.vipPrice * item.goodsQty) : formatDecimal(item.salePrice * item.goodsQty) }}
                                </div>
                            </div>
                        </div>
                        <div class="totalAmt">已换商品：¥ {{ formatDecimal(goodsTotalData.totlePrice) }}</div>
                    </div>
                  

                    <div class="orderCheckout">
                        <div v-if="route.query.state == '1'" @click="placeOrder()"
                            style="background-color: #FF3333; color: #FFFFFF;margin-top: 20px;">下单</div>
                        <div v-if="route.query.state == '2'" @click="handlePayment()"
                            style="background-color: #FFE566; color: #212121;margin-top: 20px;">结账</div>
                    </div>
                    <!-- <div>获取已点商品列表单号{{ orderBatchCode }}</div> -->
                </div>

                <div class="menuOperation">
                    <div @click="countAdd()">数量<img
                            src="https://jtmc.oss-cn-hangzhou.aliyuncs.com/pc/images/orderDishes/add.png" alt=""></div>
                    <div @click="countSubtract()">数量<img
                            src="https://jtmc.oss-cn-hangzhou.aliyuncs.com/pc/images/orderDishes/subtract.png" alt=""></div>
                    <div @click="editCount()">修改数量</div>
                    <div @click="flavorsShow()">选择口味</div>
                    <div @click="menuGoodsList[isMenuItemActive].flavor = ''">删除口味</div>
                    <div @click="delGoods()">删除商品</div>
                    <div @click="removeGoods()">清空商品</div>
                    <div @click="remarkModal()">整单备注</div>
                    <!-- <div>叫起</div> -->
                    <!-- <div>{{ priceList.priceList }}</div> -->
                </div>
            </div>

            <div class="boxRight">
                <div class="goodsBox">
                    <div class="goodsLeft">
                        <div class="menuScroll">
                              <div class="goodsMenu-ff">
                                <div class="goodsMenu">
                                <div class="title_box" :class="{ TypeActive: isTypeActive == '-1' }" @click="changeType('', '-1')">
                                    <div class="title-out"><div class="title">全部</div></div>
                                    
                                </div>
                                <div class="title_box" v-for="(item, index) in GoodsTypeList" :key="index"
                                :class="{ TypeActive: index == isTypeActive}" @click="changeType(item, index)">
                                <div class="title-out"><div class="title">{{item.goodsTypeName }}</div></div>
                                </div>
                                </div>
                            </div>

                        </div>
                        <div class="sCodeSearch">
                            <div class="SearchBtn" @click="keyPressShow = true">按简码搜索</div>
                            <div class="SearchPanel" v-if="keyPressShow">
                                <div class="SearchHead">
                                    <div class="SearchBar">
                                        <div>{{ goodsCode }}</div>
                                        <span @click="SearchBtn()">搜索</span>
                                    </div>
                                    <img src="https://jtmc.oss-cn-hangzhou.aliyuncs.com/pc/images/orderDishes/close.png"
                                        style="cursor: pointer;" @click="keyPressShow = false">
                                </div>
                                <div class="SearchKey">
                                    <div v-for="(item, index) in keyboard" :key="index" @click="keyPress(item)">{{ item }}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="goodsRight">
                        <div class="goodsRight-item" v-for="(item, index) in GoodsList" :key="index" @click="addGoods(item)">
                            <div class="goodsItem" v-if="item.state == '1'" >
                                <div class="goodsLogoS">
                                    <img class="img-jinbi" src="https://oss.jtmckj.com/wmp/qnjg/center/icon_jinbi.png" alt=""> 
                                    <img v-if="item.attachment" :src="item.attachment" class="goodsLogo">
                                    <img v-else :src="PCMaterialPic" class="goodsLogo">
                                    <div class="goodsVipPrice">会员价:￥{{ item.vipPrice }}</div>
                                </div>
                                <div class="goodsName"><span>{{ item.groupTypeName }}</span>{{ item.goodsName }}</div>
                                <div class="goodsPrice">￥{{ item.salePrice }}</div>
                                <div class="Mask" v-if="item.isEstmClear == '1'" @click.stop>
                                    <div>已售罄</div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="goodsPage" v-if="totalPages > 1">
                            <div @click="PageUp()" :class="{ disbPages: disbPageUp == true }">上一页</div>
                            <div @click="PageDown()" :class="{ disbPages: disbPageDown == true }">下一页</div>
                        </div>
                        <div class="goodsItem holde"></div>
                        <div class="goodsItem holde"></div>
                        <div class="goodsItem holde"></div>
                        <div class="goodsItem holde"></div>
                        <div class="goodsItem holde"></div>
                    </div>
                </div>
            </div>
        </div>

        <div>
            <el-dialog title="修改数量" v-model="digitaShow" width="22%" destroy-on-close :show-close="false" center
                class="menuDialog">
                <div class="digitalPanel">
                    <el-input v-model="tempNum" @input="oninput()" @keydown.prevent></el-input>
                    <div class="digitalNum">
                        <div class="numBtn" @click="oninput('1')">1</div>
                        <div class="numBtn" @click="oninput('2')">2</div>
                        <div class="numBtn" @click="oninput('3')">3</div>
                        <div class="numBtn" @click="delinput(tempNum)"><img
                                src="https://jtmc.oss-cn-hangzhou.aliyuncs.com/pc/images/orderDishes/del.png"
                                style="width: 40px; height: auto;"></div>
                        <div class="numBtn" @click="oninput('4')">4</div>
                        <div class="numBtn" @click="oninput('5')">5</div>
                        <div class="numBtn" @click="oninput('6')">6</div>
                        <div class="numBtn" @click="removeinput()">删除</div>
                        <div class="numBtn" @click="oninput('7')">7</div>
                        <div class="numBtn" @click="oninput('8')">8</div>
                        <div class="numBtn" @click="oninput('9')">9</div>
                        <div class="numBtn" @click="oninput('0')">0</div>
                    </div>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="digitaShow = false">取 消</el-button>
                        <el-button @click="subNum()">确 定</el-button>
                    </span>
                </template>
            </el-dialog>

            <el-dialog title="选择口味" v-model="tasteShow" width="45%" destroy-on-close :show-close="false" center
                class="menuDialog">
                <div class="tasteContent">
                    <div class="tasteClass">
                        <div @click="changeFlavor('', '-1')" :class="{ FlavorActive: isFlavorActive == '-1' }">全部</div>
                        <div v-for="(item, index) in flavorList" :key="index" @click="changeFlavor(item, index)"
                            :class="{ FlavorActive: index == isFlavorActive }">{{ item.name }}</div>
                    </div>
                    <div class="tasteList">
                        <div class="tasteItem" v-for="(item, index) in flavorItemS" :key="index" @click="ChoseFlavor(item)"
                            :class="{ tasteActive: item.state }">{{ item.name }}</div>
                    </div>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="tasteShow = false">取 消</el-button>
                        <el-button @click="subFlavor(thisGoodsFlavor)">确 定</el-button>
                    </span>
                </template>
            </el-dialog>

            <el-dialog title="整单备注" v-model="remarkShow" width="45%" destroy-on-close :show-close="false" center
                class="menuDialog">
                <div class="remarkContent">
                    <textarea cols="30" rows="10" placeholder="请输入口味备注" v-model="remark"></textarea>
                    <div @click="remark = ''">清除</div>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="remarkShow = false">取 消</el-button>
                        <el-button @click="remarkShow = false, orderRemark = remark">确 定</el-button>
                    </span>
                </template>
            </el-dialog>

            <ComboSelect v-if="packGoodsShow" v-model="packGoodsShow" :modalItemData="modalItemData" :toolPackDetail="PackDetail" @cancel="packGoodsShow = false" @confirm="packAllSub"/>
            <el-dialog title="规格" v-model="priceShow" width="15%" destroy-on-close :show-close="false" center
                style="border-radius: 10px;" class="FlavorDialog">
                <div style="padding: 10px 0; text-align: center; cursor: pointer; background-color: #E6E6E6; margin-bottom: 10px; border-radius: 10px;"
                    v-for="(item, index) in priceTypes.priceList" :key="index" @click="setPriceIndex(index)"
                    :class="{ setPrices: setPriceIndexVal == index }">
                    {{ item.goodsName + '（' + item.uomName + '）' }}<span v-if="item.isEstmClear == '1'">(沽清)</span>
                </div>
                <div v-for="(zv,zk) in modFlavor" :key="zk">
                    <div>
                        {{ zv.Name }}
                        <!-- <span>(多选)</span> -->
                        <span v-if="zv.IsMultiple == '1'">(多选)</span>
                        <span v-if="zv.IsMultiple != '1'">(单选)</span>
                    </div>
                    <div class="modFlavor">
                        <div v-for="(item, index) in zv.FlavorStr" :key="index"
                            @click="modFlavorChange(zv.IsMultiple,zk,index)" :class="{ isActs: item.isAct == true }">{{
                                item.name }}</div>
                    </div>
                </div>
                <div class="btnS">
                    <div @click="priceShow = false" class="btn">取消</div>
                    <div @click="priceIndex(setPriceIndexVal)" class="btn">确定</div>
                </div>
            </el-dialog>
        </div>

    </div>
</template>

<script setup>
import Api from '@/api'
import useConfigStore from '@/store/config'
import useGoodsStore from '@/store/goods'
import ls from "@/lib/ls";
import { formatDecimal } from '@/utils/chenhao'
import { getLocalIPv4 } from "@/utils/getip.js";
import ComboSelect from '@/views/components/ComboSelect.vue'
const PCMaterialPic = useConfigStore().shopInfo.PCMaterialPic
const router = useRouter()

const route = useRoute()
const configStore = useConfigStore()
const goodsStore = useGoodsStore()
const digitaShow = ref(false)
const tasteShow = ref(false)
const remarkShow = ref(false)
const keyPressShow = ref(false)
const packGoodsShow = ref(false)
const tempNum = ref('')
const GoodsList = ref('')
const modalItemData = ref({})
const PackDetail = ref({})
const PackFlavor = ref('')
const menuGoodsList = ref([])
const orderRemark = ref('')
const isMenuItemActive = ref('0')
const isTypeActive = ref('-1')
const tool = ref(configStore.tool)

const isVipPay = ref(false) // 本单是否是用vip会员价支付


// ---------------------------------------------------- 获取口味 -------------------------------------------------------
const flavorList = ref([])
const flavorItemS = ref([])
const isFlavorActive = ref('-1')
const priceShow = ref(false)
const getFlavorList = ()=>{
 Api.Common.PcObjProcess.Do({ functionName: "GetFlavorPc", "contentData":{"typeCode":"577"}})
     .then(res => {
         console.log(res.result);
         flavorList.value = res.result
         res.result.forEach(item=>{
           Api.Common.PcObjProcess.Do({ functionName: "GetFlavorPc", "contentData":{"typeCode":item.code}})
             .then(resSec => {
                 resSec.result.map(vi=>vi.state = false)
                 flavorList.value.find(v=>{
                   if(v.code == item.code){
                     v.arr = resSec.result
                   }
                 })
                 console.log(flavorList.value);
                 
             })
             .catch(err=>{

             })
         })
         // this.FlavorList = resp.result
     })
     .catch(err=>{

     })
}
getFlavorList()

//商品分类列表
const GoodsTypeList = ref('')
const GetGoodsTypeOrg = () => {
    Api.Common.PcObjProcess.Do({ "functionName": "GetGoodsTypeOrg", "orgCode": "0004", "contentData": "" })
        .then(res => {
            console.log(res)
            GoodsTypeList.value = res.result
        })
}
const changeType = (item, index) => {
    if (index == isTypeActive.value) {
        return
    } else {
        isTypeActive.value = index
        let typeCode = ''
        if (item) {
            typeCode = item.goodsTypeCode
        } else {
            typeCode = ''
        }
        GoodsList.value = ''
        goodsInfoPar.value = { pageIndex: 1, pageSize: 14, shortName: "", goodsType: typeCode }
        getGoodsInfo()
    }
}

const totalPages = ref('')

//获取商品列表
const goodsInfoPar = ref({ pageIndex: 1, pageSize: 14, shortName: "" })
const getGoodsInfo = () => {
    // 过滤筛选  分类选择  简码搜索
    function filterItems(items, goodsType, shortName) {
        if(goodsType && shortName){
            return items.filter(item =>
                item.goodsType.split(',').includes(goodsType) && (item.shortName.includes(shortName) || item.goodsName.includes(shortName))
            );
        }else if(!goodsType && shortName){
            return items.filter(item =>
                (item.shortName.includes(shortName) || item.goodsName.includes(shortName))
            );
        }else if(goodsType && !shortName){
            return items.filter(item =>
                item.goodsType.split(',').includes(goodsType) 
            );
        }else{
            return items
        }
    }
    // 分页
    function filterAndPaginateItems(items,pageIndex, pageSize) {
        // 计算分页起始和结束索引
        const startIndex = (pageIndex - 1) * pageSize;
        const endIndex = startIndex + pageSize;

        // 获取分页后的数据
        const paginatedItems = items.slice(startIndex, endIndex);

        return paginatedItems;
    }

    const arr = filterItems(goodsStore.goodsList, goodsInfoPar.value.goodsType, goodsInfoPar.value.shortName);
    const filteredItems = filterAndPaginateItems(arr,goodsInfoPar.value.pageIndex,goodsInfoPar.value.pageSize )
    let res = {
        totalCount:arr.length,
        data:filteredItems
    }
    // Api.Common.PcObjProcess.Do({ "functionName": "getGoodsInfo", "contentData": goodsInfoPar.value })
        // .then(res => {
            console.log(res)
            isPageBtn(goodsInfoPar, res.totalCount)
            totalPages.value =  Math.ceil(res.totalCount / goodsInfoPar.value.pageSize)
            if (res.data.length > 0) {
                GoodsList.value = res.data
            } else {
                goodsInfoPar.value.pageIndex--
            }
        // })
}
//翻页按钮是否显示
const disbPageUp = ref(false)
const disbPageDown = ref(false)
const isPageBtn = (goodsInfoPar, totalCount) => {
    console.log(goodsInfoPar, totalCount)
    let num1 = totalCount;
    let num2 = goodsInfoPar.value.pageSize;
    let quotient = '';
    if (num1 % num2 == 0) {
        quotient = parseInt(num1 / num2)
    } else {
        quotient = parseInt(num1 / num2) + 1
    }
    if (goodsInfoPar.value.pageIndex <= 1) {
        disbPageUp.value = true
    } else { disbPageUp.value = false }
    if (goodsInfoPar.value.pageIndex >= quotient) {
        disbPageDown.value = true
    } else { disbPageDown.value = false }
}
//上下页
const PageUp = () => {
    if (goodsInfoPar.value.pageIndex > '1') {
        goodsInfoPar.value.pageIndex--
        getGoodsInfo()
    }
}
const PageDown = () => {
    goodsInfoPar.value.pageIndex++
    getGoodsInfo()
}
const indexStrV = ref(0)
const addGoods = (i) => {
    console.log('i', i)
    isMenuItemActive.value = '0'
    if (i.type == '2') {
        packModalShow(i) // 选套餐
    } else {
        if (i.priceList.length > 1 || i.goodsFlavor) {
            priceType(i) // 选规格
            
        }  else {
            let detail = {
                isNew: "1",
                itemCode: i.priceList[0].itemCode,
                goodsCode: i.priceList[0].goodsCode,
                goodsName: i.priceList[0].goodsName,
                uomCode: i.priceList[0].uomCode,
                uomName: i.priceList[0].uomName,
                flavor: "",
                salePrice: i.priceList[0].salePrice,
                goodsQty: "1",
                vipPrice: i.priceList[0].vipPrice,
                payAmt: i.priceList[0].payAmt,
                producePoint:i.priceList[0].producePoint
            }
            menuGoodsList.value.unshift(detail)
            let top = []
            let down = []
            menuGoodsList.value.map(e => {
                if (e.isNew == '0') {
                    top.push(e)
                } else {
                    down.push(e)
                }
            })
            menuGoodsList.value = []
            menuGoodsList.value.push(...top)
            menuGoodsList.value.push(...down)
            goodsTotal()
        }
    }
}
// 选规格
const priceTypes = ref([])
const modFlavor = ref('')
const priceType = (i) => {
    console.log(i);
    
    let flavors = ''
    if (i.goodsFlavor) {
        flavors = JSON.parse(i.goodsFlavor)
        console.log(flavors);
        flavors.forEach(item=>{
            // item.FlavorStr = item.FlavorStr.split(',')
            item.FlavorStr = [item.FlavorStr]
            let a = {
                name: '',
                isAct: false
            }
            let data = []
            item.FlavorStr.map(e => {
                a.name = e
                data.push(JSON.parse(JSON.stringify(a)))
            })
            item.FlavorStr = data
        })
        
    }
    modFlavor.value = flavors
    console.log(modFlavor.value);
    if(modFlavor.value){
        modFlavor.value.forEach((vz,vk)=>{
            vz.FlavorStr.forEach((v, k) => {
                    
                    if(typeof v.name == 'string'){
                        
                        const str = v.name;
    
                        // 替换中文逗号为英文逗号
                        const normalizedStr = str.replace(/，/g, ',');
                        // 使用英文逗号分隔字符串
                        const parts = normalizedStr.split(',');
                        // 将每个部分转换为对象
                        const result = parts.map(part => {
                            // 默认值
                            let name = part.trim();
                            let addprice = 0;
                            let isAct = false;
                            // 检查是否有#，设置isAct
                            if (name.includes('#')) {
                                isAct = true;
                                name = name.replace('#', '').trim();
                            }
                            // 检查是否有*，设置addprice
                            const match = name.match(/\*(\d+)$/);
                            if (match) {
                                addprice = parseInt(match[1], 10);
                                name = name.replace(match[0], '').trim();
                            }
                            return { name, addprice, isAct };
                        });
                        v.list = result
                    }
                  
                    
            })

            console.log(vz);
            if(vz.FlavorStr[0].list){
                vz.FlavorStr = vz.FlavorStr[0].list
            }
            console.log(vz);

        })
       
    }
    
    priceShow.value = true
    i.indexStr = indexStrV.value++
    priceTypes.value = i
    priceTypes.value = JSON.parse(JSON.stringify(priceTypes.value))
}
const setPriceIndexVal = ref('0')
const setPriceIndex = (index) => {
    setPriceIndexVal.value = index
}
const priceIndex = (index) => {
    if(priceTypes.value.priceList[setPriceIndexVal.value].isEstmClear == '1'){
        ElNotification({
            title: '提示',
            message: '该规格已设为估清',
            type: 'error',
        }) 
        return
    }
    console.log(index);
    console.log(modFlavor.value);
    
    priceShow.value = false
    let a = priceTypes.value.priceList[index]
    console.log('a :>> ', a);
    priceTypes.value.priceList = []
    priceTypes.value.priceList.push(a)
    let temp = { goodsQty: '1',flavor: [] }
    
    console.log(priceTypes.value);
    
    console.log(modFlavor.value);
    if(priceTypes.value.goodsFlavor){
        modFlavor.value.forEach(item=>{
            item.FlavorStr.map(e => {
                if (e.isAct == true) {
                    temp.flavor.push(e.name)
                }
            })
        })
    }
   
    temp.flavor = temp.flavor.join(','); // 使用中文逗号
  
    Object.assign(priceTypes.value, temp)
 
    console.log(priceTypes.value);
    priceTypes.value.producePoint = priceTypes.value.priceList[0].producePoint
    priceTypes.value.isNew = '1'
    priceTypes.value.uomName = priceTypes.value.priceList[0].uomName
    priceTypes.value.uomCode = priceTypes.value.priceList[0].uomCode
    menuGoodsList.value.unshift(JSON.parse(JSON.stringify(priceTypes.value)))
    let top = []
    let down = []
    menuGoodsList.value.map(e => {
        // console.log('e :>> ', e);
        if (e.isNew == '0') {
            top.push(e)
        } else {
            e.isNew = '1'
            down.push(e)
        }
    })
    menuGoodsList.value = []
    menuGoodsList.value.push(...top)
    menuGoodsList.value.push(...down)
    goodsTotal()
    console.log(menuGoodsList.value)
}
//规格口味
const modFlavorChange = (isMultiple,zk,index) => {
    console.log(modFlavor.value);
    
    if (isMultiple == '1') {
        modFlavor.value[zk].FlavorStr[index].isAct = !modFlavor.value[zk].FlavorStr[index].isAct
    } else {
        modFlavor.value[zk].FlavorStr.map(e => {
            e.isAct = false
        })
        modFlavor.value[zk].FlavorStr[index].isAct = true
    }
}
const editItem = (i, s) => {
    console.log(i, s)
    isMenuItemActive.value = s;
}

const packModalShow = (i) => {
    console.log(i)
    PackFlavor.value = ''
    packGoodsShow.value = true
    i.indexStr = indexStrV.value++
    i.priceList[0].detail.map(e => {
        e.allQty = 0
        console.log(e.goodsDetail);
        
        e.goodsDetail.map(s => {
            if(s.isEstmClear != '1'){
                e.allQty = e.allQty + Number(s.defaultQty)
            }
            if(s.isEstmClear == '1'){
                s.defaultQty = 0
            }
        })
    })
    console.log(i)
    i.priceList[0].detail.map(e => {
        e.goodsDetail.map(s => {
            if (typeof (s.goodsFlavor) != 'string') {
                s.goodsFlavor.map(v => {
                    v.flavorState = false
                })
            }
        })
    })
    modalItemData.value = i
    console.log(modalItemData.value.priceList[0].detail);
    modalItemData.value.priceList[0].detail.forEach(detail=>{
        detail.goodsDetail.forEach(detailV=>{
            let flavor = detailV.goodsFlavor
            if (flavor) {
                let newFlavor = ''
                if (typeof (flavor) == 'string') {
                    newFlavor = JSON.parse(flavor)
                } else {
                    newFlavor = flavor
                }
                newFlavor.map(e => {
                    if (e.flavorState == undefined) {
                        e.flavorState = false
                    }
                })
                console.log(newFlavor);
                newFlavor.forEach(item=>{
                    if(typeof item.FlavorStr == 'string'){
                                
                                const str = item.FlavorStr;
            
                                // 替换中文逗号为英文逗号
                                const normalizedStr = str.replace(/[，,]/g, ',');
                                // 使用英文逗号分隔字符串
                                const parts = normalizedStr.split(',');
                                // 将每个部分转换为对象
                                const result = parts.map(part => {
                                    // 默认值
                                    let uomName = part.trim();
                                    let addprice = 0;
                                    let select = false;
                                    // 检查是否有#，设置select
                                    if (uomName.includes('#')) {
                                        select = true;
                                        uomName = uomName.replace('#', '').trim();
                                    }
                                    // 检查是否有*，设置addprice
                                    const match = uomName.match(/\*(\d+)$/);
                                    if (match) {
                                        addprice = parseInt(match[1], 10);
                                        uomName = uomName.replace(match[0], '').trim();
                                    }
                                    return { uomName, addprice, select };
                                });
                                console.log(result);
                                
                                item.sizeList = result
                                
                    }
                })
                
                // PackFlavor.value = newFlavor
                detailV.goodsFlavor = newFlavor

                const result = newFlavor.map(vitem => {
                // 获取 sizeList 中 select 为 true 的 uomName 并拼接成字符串
                const flavor = vitem.sizeList
                    .filter(obj => obj.select)        // 过滤出 select 为 true 的对象
                    .map(obj => obj.uomName)          // 提取每个符合条件的 uomName
                    .join(',');                       // 使用 ',' 连接成一个字符串
                
                return flavor;                      // 直接返回拼接后的字符串
                });
                console.log(result);
                
                detailV.flavor = result.filter(obj => obj).join(',');
                console.log(detailV)
            }
        })
    })
    chosePack(modalItemData.value.priceList[0].detail[0].goodsDetail, '0')
}
// 选择套餐
const PackIndex = ref(0)
const operType = ref('')
const chosePack = (detail, index) => {
    console.log(detail);
    console.log(modalItemData.value.priceList[0].detail);
    modalItemData.value.priceList[0].detail.forEach(item=>{
        item.goodsDetail.map(v=>{
            v.choiceType = item.choiceType
            v.isSelect = false
            v.operType = item.operType
        })
    })
    operType.value = modalItemData.value.priceList[0].detail[index].operType
    // let choiceType  = modalItemData.value.priceList[0].detail[index].choiceType
    PackIndex.value = index
    // return
    flavorIndex.value = 0
    PackDetail.value = detail
    // PackDetail.value.map(item=>{
    //     item.choiceType = choiceType
    //     item.isSelect = false
    //     item.operType = operType.value
    // })
    
    // getPackFlavorS(detail[0].goodsFlavor, '0')
    return
    if (flavor) {
        let newFlavor = JSON.parse(flavor)[0].FlavorStr.split(',')
        let tempList = []
        for (let i = 0; i < newFlavor.length; i++) {
            let tempData = { flavorName: '', flavorState: false }
            tempData.flavorName = newFlavor[i]
            tempList.push(tempData)
        }
        PackFlavor.value = tempList
        console.log(PackFlavor.value)
    }
}
// 获取套餐单品口味
const flavorIndex = ref(0)
// const getPackFlavorS = (flavor, index) => {
//     flavorIndex.value = index
//     if (flavor) {
//         let newFlavor = ''
//         if (typeof (flavor) == 'string') {
//             newFlavor = JSON.parse(flavor)
//         } else {
//             newFlavor = flavor
//         }
//         newFlavor.map(e => {
//             if (e.flavorState == undefined) {
//                 e.flavorState = false
//             }
//         })
//         console.log(newFlavor);
//         newFlavor.forEach(item=>{
//             if(typeof item.FlavorStr == 'string'){
                        
//                         const str = item.FlavorStr;
    
//                         // 替换中文逗号为英文逗号
//                         const normalizedStr = str.replace(/[，,]/g, ',');
//                         // 使用英文逗号分隔字符串
//                         const parts = normalizedStr.split(',');
//                         // 将每个部分转换为对象
//                         const result = parts.map(part => {
//                             // 默认值
//                             let uomName = part.trim();
//                             let addprice = 0;
//                             let select = false;
//                             // 检查是否有#，设置select
//                             if (uomName.includes('#')) {
//                                 select = true;
//                                 uomName = uomName.replace('#', '').trim();
//                             }
//                             // 检查是否有*，设置addprice
//                             const match = uomName.match(/\*(\d+)$/);
//                             if (match) {
//                                 addprice = parseInt(match[1], 10);
//                                 uomName = uomName.replace(match[0], '').trim();
//                             }
//                             return { uomName, addprice, select };
//                         });
//                         console.log(result);
                        
//                         item.sizeList = result
                        
//             }
//         })
        
//         // PackFlavor.value = newFlavor
//         PackDetail.value[flavorIndex.value].goodsFlavor = newFlavor

//         const result = newFlavor.map(vitem => {
//         // 获取 sizeList 中 select 为 true 的 uomName 并拼接成字符串
//         const flavor = vitem.sizeList
//             .filter(obj => obj.select)        // 过滤出 select 为 true 的对象
//             .map(obj => obj.uomName)          // 提取每个符合条件的 uomName
//             .join(',');                       // 使用 ',' 连接成一个字符串
        
//         return flavor;                      // 直接返回拼接后的字符串
//         });
//         console.log(result);
        
//         PackDetail.value[flavorIndex.value].flavor = result.filter(obj => obj).join(',');
//         console.log(PackDetail.value[flavorIndex.value].goodsFlavor)
//     }
// }

// 套餐提交
const packAllSub = (itemS) => {
    console.log(itemS);
    let item = []
    itemS.map(e => {
        e.goodsDetail.map(s => {
            item.push(s)
        })
    })
    item.forEach(v=>{
        if(v.choiceType == '1' && !v.isSelect && v.operType =='0'){
                v.defaultQty = 0
        }
    })
    let allQty = modalItemData.value.priceList[0].detail[PackIndex.value].allQty
    let maxQty = modalItemData.value.priceList[0].detail[PackIndex.value].maxQty
    modalItemData.value.count = '1'
        item.map(e => {
            e.flavors = e.flavor
            // e.flavors = []
            // if (typeof (e.goodsFlavor) != 'string') {
            //     e.goodsFlavor.map(s => {
            //         if (s.flavorState == true) {
            //             e.flavors.push(s.Name)
            //         }
            //     })
            // }
        })
        let modalItemDataS = JSON.parse(JSON.stringify(modalItemData.value))
        modalItemDataS.priceList[0].detail[PackIndex.value].goodsDetail = []
        let packPrice = modalItemData.value.salePrice // 获取套餐的销售价格
        let vipPackPrice = modalItemData.value.vipPrice // 获取套餐的vip价格
        let a = []
        let tots = 0
        item.map((e, i) => {
            let b = {
                unit: e.salePrice,
                tot: e.salePrice * e.defaultQty
            }
            a.push(b)
            tots += b.tot
            if (e.defaultQty > 0) {
                modalItemDataS.priceList[0].detail[PackIndex.value].goodsDetail.push(e)
            }
        })
        let c = []
        let d = []
        a.map(e => {
            c.push(packPrice * (e.tot / tots))
            d.push(vipPackPrice * (e.tot / tots))
        })
        item = item.filter(v => v.defaultQty > 0);
        let percentPriceTemp = 0
        let vipPercentPriceTemp = 0
        for (let i = 0; i < item.length; i++) {
            item[i].percentPrice = parseInt(c[i])
            item[i].vipPercentPrice = parseInt(d[i])
            percentPriceTemp += item[i].percentPrice
            vipPercentPriceTemp += item[i].vipPercentPrice
        }
        item[item.length - 1].percentPrice += (packPrice - percentPriceTemp)
        item[item.length - 1].vipPercentPrice += (vipPackPrice - vipPercentPriceTemp)
        // return
        let goodsDetail = modalItemDataS.priceList[0].detail[PackIndex.value].goodsDetail
     
        modalItemDataS.priceList[0].detail = goodsDetail
        console.log(modalItemDataS);
        console.log(modalItemDataS.priceList[0]);
        // 改造成换菜接口要的格式
         let detail = {
                isNew: "1",
                itemCode: modalItemDataS.priceList[0].itemCode,
                goodsCode: modalItemDataS.priceList[0].goodsCode,
                goodsName: modalItemDataS.priceList[0].goodsName,
                uomCode: modalItemDataS.priceList[0].uomCode,
                uomName: modalItemDataS.priceList[0].uomName,
                flavor: "",
                salePrice: modalItemDataS.priceList[0].salePrice,
                goodsQty: "1",
                itemType:'2',
                vipPrice: modalItemDataS.priceList[0].vipPrice,
                payAmt: modalItemDataS.priceList[0].payAmt,
                indexStr:modalItemDataS.indexStr,
                subDetail:modalItemDataS.priceList[0].detail
        }
        detail.subDetail.forEach(item=>{
            item.indexStr = detail.indexStr
            item.goodsPriceCode = detail.goodsCode
            item.goodsQty = item.defaultQty
            item.itemType = '3'
        })
        console.log(detail);
        menuGoodsList.value.unshift(JSON.parse(JSON.stringify(detail)))
        packGoodsShow.value = false
        goodsTotal()
}
// 商品被沽清后 刷新商品
watch(configStore.isGoodChange,(newValue,oldValue)=>{
    if(hasCodeInTargetArray(menuGoodsList.value,configStore.isGoodChange.goodsCode)){
        alert('已店商品价格发生变动或已售罄，请重新点单')
        window.location.reload()
    }else{
        onInit()
    }
})
// 对比数组 判断两数组中是否有相同的
const hasCodeInTargetArray=(objectArray, targetArray)=> {
  return objectArray.some(obj => {
      return targetArray.some(target => obj.goodsCode == target);
  });
}

//数量加
const countAdd = () => {
    console.log(menuGoodsList.value);
    // 是否是新增的商品
    if(menuGoodsList.value[isMenuItemActive.value].isNew == '1'){
        menuGoodsList.value[isMenuItemActive.value].goodsQty++
    }else{
        console.log(checkItemCodeExists());
        if(checkItemCodeExists()){
            if (menuGoodsList.value[isMenuItemActive.value].goodsQty >= 999) {
            alert('超出最大数量')
        } else {
           
            let itemCode = menuGoodsList.value[isMenuItemActive.value].itemCode
            OrderDetail.value.consumeList.forEach(item => {
                if (item.itemCode == itemCode) {
                    item.goodsQty --
                }
            });
            menuGoodsList.value[isMenuItemActive.value].goodsQty++
        }
        }else{
            ElNotification({
                title: '提示',
                message: '不可超出该商品已点数量',
                type: 'error',
            })
        }
    }
   
    goodsTotal()
    
}
//数量减
const countSubtract = () => {
    if(menuGoodsList.value[isMenuItemActive.value].isNew == '1'){
        if (menuGoodsList.value[isMenuItemActive.value].goodsQty -1 <= 0) {
            ElNotification({
                title: '提示',
                message: '数量不可为0',
                type: 'warning',
            })
            return
        }
        menuGoodsList.value[isMenuItemActive.value].goodsQty--
    }else{
        menuGoodsList.value[isMenuItemActive.value].goodsQty--
        if(checkItemCodeExists()){
        let itemCode = menuGoodsList.value[isMenuItemActive.value].itemCode
        console.log(itemCode);
        OrderDetail.value.consumeList.forEach(item => {
            if (item.itemCode == itemCode) {
                console.log(item);
                item.goodsQty ++ 
            }
        });

        }else{
            console.log({...menuGoodsList.value[isMenuItemActive.value]});
            let obj = {...menuGoodsList.value[isMenuItemActive.value]}
            obj.goodsQty = 1
            OrderDetail.value.consumeList.push(obj)
        }
        if (menuGoodsList.value[isMenuItemActive.value].goodsQty <= 0) {
        
            menuGoodsList.value.splice(isMenuItemActive.value, 1);
        }
    }
    
    goodsTotal()
    
}
// 查找上方商品是否有和下方数组相同的
const checkItemCodeExists = () => {
    const activeMenuItem = menuGoodsList.value[isMenuItemActive.value];
    const activeItemCode = activeMenuItem.itemCode;

    // 遍历 consumeList，查找是否存在相同 itemCode 的项
    for (let consumeItem of OrderDetail.value.consumeList) {
        if (consumeItem.itemCode === activeItemCode) {
            return true; // 找到相同的 itemCode，返回 true
        }
    }

    return false; // 没有找到相同的 itemCode，返回 false
}

//打开数量输入器
const editCount = () => {
    console.log(menuGoodsList.value[isMenuItemActive.value]);
    if (menuGoodsList.value[isMenuItemActive.value]) {
        tempNum.value = menuGoodsList.value[isMenuItemActive.value].goodsQty
        digitaShow.value = true
    }
}
//修改数量
const oninput = (n) => {
    tempNum.value += n
    if(tempNum.value > menuGoodsList.value[isMenuItemActive.value].maxNum){
        ElNotification({
            title: '提示',
            message: '不可超出该商品已点数量',
            type: 'warning',
        })
        tempNum.value = menuGoodsList.value[isMenuItemActive.value].maxNum
    }
  
}
const delinput = (n) => {
    if(n.length >= 1){
        tempNum.value = n.slice(0, n.length - 1)
    }else{
        tempNum.value = ''
    }
    
}
const removeinput = (n) => {
    tempNum.value = ''
}
// 修改数量确认
const subNum = () => {
    if(!tempNum.value){
        ElNotification({
            title: '提示',
            message: '请输入正确数量',
            type: 'warning',
        })
        return
    }
    digitaShow.value = false
    if(menuGoodsList.value[isMenuItemActive.value].isNew == '1'){
        menuGoodsList.value[isMenuItemActive.value].goodsQty = tempNum.value
    }else{
        // 计算数量差额
        const diffNum = Number(menuGoodsList.value[isMenuItemActive.value].maxNum) - Number(tempNum.value)
            // 如果上面还有相同的商品
            if(checkItemCodeExists()){
                let itemCode = menuGoodsList.value[isMenuItemActive.value].itemCode
                    OrderDetail.value.consumeList.forEach(item => {
                        if (item.itemCode == itemCode) {
                            item.goodsQty = diffNum
                        }
                });
            }else{
                let obj = {...menuGoodsList.value[isMenuItemActive.value]}
                obj.goodsQty = diffNum
                OrderDetail.value.consumeList.push(obj)
            }
            menuGoodsList.value[isMenuItemActive.value].goodsQty = tempNum.value
            menuGoodsList.value = menuGoodsList.value.filter(obj => obj.goodsQty != 0);
    }
    
    goodsTotal()
}
//商品合计
const goodsTotalData = ref({
    totalCount: 0, // 总数
    totlePrice: 0, // 总价格
    totleVipPrice: 0, // 会员价格
    calcVipPrice:0 // 用来计算vip价格的
})

const goodsTotal = () => {
    console.log(isVipPay.value);
    // 过滤掉数量为0的商品
    OrderDetail.value.consumeList = OrderDetail.value.consumeList.filter(obj => obj.goodsQty != 0);

    goodsTotalData.value = {
        totalCount: 0,
        totlePrice: 0,
        totleVipPrice: 0,
        calcVipPrice:0,
    }
    menuGoodsList.value.map(e => {
        console.log('e :>> ', e);
        console.log('Number(e.vipPrice) * Number(e.goodsQty) :>> ', Number(e.vipPrice) * Number(e.goodsQty));
        if (e.isNew == '0') {
            goodsTotalData.value.totalCount -= Number(e.goodsQty)
            if(isVipPay.value){
                goodsTotalData.value.totlePrice -= Number(e.vipPrice) * Number(e.goodsQty)
                goodsTotalData.value.calcVipPrice -= Number(e.vipPrice) * Number(e.goodsQty)
            }else{
                goodsTotalData.value.totlePrice -= Number(e.salePrice) * Number(e.goodsQty)
                goodsTotalData.value.calcVipPrice -= Number(e.salePrice) * Number(e.goodsQty)
            }
            goodsTotalData.value.totleVipPrice -= Number(e.vipPrice) * Number(e.goodsQty)
            
        } else {
            goodsTotalData.value.totalCount += Number(e.goodsQty)
            if(isVipPay.value){
                goodsTotalData.value.totlePrice += Number(e.vipPrice) * Number(e.goodsQty)
            }else{
                goodsTotalData.value.totlePrice += Number(e.salePrice) * Number(e.goodsQty)
            }
            goodsTotalData.value.totleVipPrice += Number(e.vipPrice) * Number(e.goodsQty)
            goodsTotalData.value.calcVipPrice += Number(e.salePrice) * Number(e.goodsQty)
        }
    })
    console.log('goodsTotalData.value :>> ', goodsTotalData.value);
}
//打开口味弹窗
const flavorsShow = () => {
    flavorItemS.value = []
    flavorList.value.map(item=>{
        flavorItemS.value.push(...item.arr)
    })
    tasteShow.value = true
    console.log(flavorItemS.value);
    
}
//选择口味组
const changeFlavor = (i, s) => {
    isFlavorActive.value = s
    flavorItemS.value = []
    console.log(i,s);
    if(s == -1){
        flavorList.value.map(item=>{
            flavorItemS.value.push(...item.arr)
        })
    }else{
        flavorItemS.value = flavorList.value[s].arr
    }

}
//测试方法
const removeElement = (arr, value) => {
    return arr.filter(function (item) {
        return item !== value;
    });
}
//选择口味
const thisGoodsFlavor = ref([])
const ChoseFlavor = (item) => {
    // var arr = [1, 2, 3, 4, 5];
    // var newValue = 3;
    // arr = removeElement(arr, newValue);
    // console.log(arr); // [1, 2, 4, 5]
    // return
    item.state = !item.state
    if (item.state) {
        thisGoodsFlavor.value.push(item.name)
    } else {
        thisGoodsFlavor.value = removeElement(thisGoodsFlavor.value, item.name);
    }
    console.log(thisGoodsFlavor.value)
}
const subFlavor = (flavor) => {
    console.log(menuGoodsList.value);
    console.log(isMenuItemActive.value);
    console.log(JSON.parse(JSON.stringify(flavor)));
    menuGoodsList.value[isMenuItemActive.value].flavor = JSON.parse(JSON.stringify(flavor)).join(',')

    tasteShow.value = false
}
// menuGoodsList[isMenuItemActive].flavors
//删除商品
const delGoods = () => {
    if (menuGoodsList.value[isMenuItemActive.value].isNew == '0') {
        OrderDetail.value.totalAmt += menuGoodsList.value[isMenuItemActive.value].salePrice * menuGoodsList.value[isMenuItemActive.value].goodsQty
        OrderDetail.value.consumeList.push(menuGoodsList.value[isMenuItemActive.value])
        // let temp = false
        // OrderDetail.value.consumeList.map(e => {
        //     if(e.locate == menuGoodsList.value[isMenuItemActive.value].locate){
        //         temp = true
        //     }
        // })
    }
    menuGoodsList.value.splice(isMenuItemActive.value, 1);
    isMenuItemActive.value = '0'
    goodsTotal()
}
//清空商品
const removeGoods = () => {
    menuGoodsList.value.map(e => {
        if (e.isNew == '0') {
            OrderDetail.value.consumeList.push(e)
            OrderDetail.value.totalAmt += e.salePrice * e.goodsQty
        }
    })
    menuGoodsList.value = []
    goodsTotalData.value = {
        totalCount: 0,
        totlePrice: 0,
        vipPrice: 0,
        calcVipPrice:0,
    }
}
//整单备注
const remark = ref('')
const remarkModal = () => {
    remarkShow.value = true
    remark.value = orderRemark.value
}
//菜品简码输入框
const goodsCode = ref('请输入菜品简码')
//键盘
const keyboard = ref(
    ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', '空格', 'shift', 'z', 'x', 'c', 'v', 'b', 'n', 'm', '清空']
)
const CapsLock = ref(false)
const keyPress = (key) => {
    //输入框
    if (key != 'shift' && key != 'SHIFT' && key != '空格' && key != '清空') {
        if (goodsCode.value == '请输入菜品简码') {
            goodsCode.value = ''
            goodsCode.value += key
        } else {
            goodsCode.value += key
        }
    }
    //空格
    if (key == '空格' && goodsCode.value != '请输入菜品简码') {
        goodsCode.value += ' '
    }
    //清空
    if (key == '清空') {
        goodsCode.value = '请输入菜品简码'
    }
    //大小写切换
    let Caps = ''
    if (key == 'shift' && !CapsLock.value) {
        CapsLock.value = !CapsLock.value
        Caps = keyboard.value.toString().toUpperCase()
        keyboard.value = Caps.split(',')
    } else if (key == 'SHIFT' && CapsLock.value) {
        CapsLock.value = !CapsLock.value
        Caps = keyboard.value.toString().toLowerCase()
        keyboard.value = Caps.split(',')
    }
}

// 简码搜索按钮
const SearchBtn = () => {
    if (goodsCode.value != '请输入菜品简码') {
        GoodsList.value = ''
        goodsInfoPar.value = { pageIndex: 1, pageSize: 14, shortName: goodsCode.value }
        console.log(goodsInfoPar.value)
        getGoodsInfo()
    } else {
        goodsInfoPar.value = { pageIndex: 1, pageSize: 14, shortName: '' }
        getGoodsInfo()
    }
}

//获取ip地址
const ip = ref("");
getLocalIPv4()
    .then((ipAddress) => {
        // 在这里处理获取到的 IP 地址
        ip.value = ipAddress;
        console.log("IP 地址:", ip.value);
    })
    .catch((error) => {
        console.error("发生错误:", error);
        // 在这里处理错误情况
    });

//挂单
const placeOrderFlag = ref(false)
const placeOrder = () => {
    let hasOld = false
    let hasNew = false
    menuGoodsList.value.forEach(item => {
        if (item.isNew === '1') {
            hasNew = true
        } else {
            hasOld = true
        }
    })
    if (!hasOld) return ElNotification({
        title: '提示',
        message: '请选择需要更换的商品',
        type: 'warning',
    })
    if (!hasNew) return ElNotification({
        title: '提示',
        message: '请选择新商品',
        type: 'warning',
    })

    if(placeOrderFlag.value){
        ElNotification({
            title: '提示',
            message: '加载中，请稍等',
            type: 'warning',
        })
        return
    }
    placeOrderFlag.value = true
    let consumeCode = ls.get("TABLE_INFO").consumeCode; // 消费单号
    // GetOrderDetail(consumeCode, route.query.state, route.query.payBatchCode)
    let contentData = {
        consumeCode: consumeCode,
        // orderBatchCode: '0004202405130001',
        // state: 1,
        detail: []
    }
    contentData.detail.push(...menuGoodsList.value)
    calculateOrderQty(contentData.detail)
    contentData={...contentData,ip:ip.value};
    Api.Common.PcObjProcess.Do({ functionName: "OpPayBatchChangeGoods", contentData })
        .then(res => {
            menuGoodsList.value = []
            ElNotification({
                title: '提示',
                message: '换菜挂单成功',
                type: 'success',
            })
            placeOrderFlag.value = false
            // router.back()
        }).catch(err=>{
            placeOrderFlag.value = false
        })
}
//下单
// const orderBatchCode = ref('')
// const placeOrder = () => {
//     let details = {}
//     let contentData = {
//         consumeCode: "0004202402050006",
//         roomCode: "0004003",
//         remark: orderRemark.value,
//         operType: "",
//         detail: []
//     }
//     menuGoodsList.value.map(e => {
//         details = {
//             itemCode: "",
//             doType: "add",
//             indexStr: "1",
//             itemType: "",
//             goodsPriceCode: "",
//             goodsCode: "",
//             goodsName: "",
//             uomCode: "",
//             uomName: "",
//             flavor: "",
//             salePrice: "",
//             orderQty: "",
//             producePoint: "000403"
//         }
//         e.priceList.map(s => {
//             details.itemCode = s.itemCode
//             details.itemType = e.type
//             details.goodsCode = e.goodsCode
//             details.goodsName = e.goodsName
//             details.uomCode = s.uomCode
//             details.uomName = s.uomName
//             details.salePrice = s.salePrice
//             details.orderQty = e.goodsQty
//             if(e.flavor){
//                 details.flavor = e.flavor.toString()
//             }
//         })
//         contentData.detail.push(details)
//     })
//     // return
//     Api.Common.PcObjProcess.Do({functionName:"orderAdd",contentData})
//     .then(res=>{
//         console.log(res)
//         menuGoodsList.value = []
//         orderRemark.value = ''
//         remark.value = ''
//         orderBatchCode.value = res.orderBatchCode
//     })
// }
const OrderDetail = ref('')
const serviceList = ref([]) // 优惠项目
const GetOrderDetail = (consumeCode, state, payBatchCode) => {
    let contentData = {
        consumeCode,
        state,
        payBatchCode
    }
    Api.Common.PcObjProcess.Do({ functionName: "GetPayBatchGoodsList", contentData })
        .then(res => {
            serviceList.value = res.result[0].serviceList
            let orderDetails = res.result[0].consumeList
            OrderDetail.value = res.result[0]
            OrderDetail.value.consumeList = []
            console.log(OrderDetail.value)
            let locate = '0'
            let Amt = {
                totalAmt: 0
            }
            orderDetails.map(i => {
                let detail = {
                    isUseVipPay:i.isUseVipPay,
                    locate: locate++,
                    isNew: "0",
                    maxNum:i.orderQty,
                    itemCode: i.itemCode,
                    goodsCode: i.goodsCode,
                    goodsName: i.goodsName,
                    uomCode: i.uomCode,
                    uomName: i.uomName,
                    flavor: i.flavor,
                    salePrice: i.salePrice,
                    goodsQty: i.orderQty,
                    vipPrice: i.vipPrice,
                    payAmt: i.payAmt,
                }
                if(detail.isUseVipPay){
                    isVipPay.value = true
                }
                Amt.totalAmt += i.payAmt
                OrderDetail.value.consumeList.push(detail)
            })
            Object.assign(OrderDetail.value, Amt)
            console.log('orderDetails :>> ', orderDetails);
        })
}

//换菜
const replaceDishes = (i, s) => {
   
    OrderDetail.value.totalAmt -= i.payAmt
    menuGoodsList.value.unshift(i) // 下面的商品添加选中的那个
    // 商品排序
    let top = []
    let down = []
    menuGoodsList.value.map(e => {
        if (e.isNew == '0') {
            top.push(e)
        } else {
            down.push(e)
        }
    })
    menuGoodsList.value = []
    menuGoodsList.value.push(...top)
    menuGoodsList.value.push(...down)
    console.log(menuGoodsList.value);
    
    // console.log(OrderDetail.value.consumeList[s])
    OrderDetail.value.consumeList.splice(s, '1') // 上面的商品移除选中的那个
    goodsTotal()
}
//初始化
const onInit = async () => {
    ls.remove('GOOD_SESSION') // 清除掉版本号（初始化获取商品数据前）
    GetGoodsTypeOrg()
    await goodsStore.UpdateAll()
    getGoodsInfo()
    let consumeCode = ls.get("TABLE_INFO").consumeCode; // 消费单号
    GetOrderDetail(consumeCode, route.query.state, route.query.payBatchCode)
}
onInit()

// -----------------换菜支付-------------------------
const handlePaymentFlag = ref(false)
const handlePayment = async(params) => {
    
        
    let hasOld = false
    let hasNew = false
    let oldItemCode = []
    let newItemCode = []
    menuGoodsList.value.forEach(item => {
        if (item.isNew === '1') {
            hasNew = true
            newItemCode.push(item.itemCode)
        } else {
            hasOld = true
            oldItemCode.push(item.itemCode)
        }
    })
    if (!hasOld) return ElNotification({
        title: '提示',
        message: '请选择需要更换的商品',
        type: 'warning',
    })
    if (!hasNew) return ElNotification({
        title: '提示',
        message: '请选择新商品',
        type: 'warning',
    })
    if(handlePaymentFlag.value){
        ElNotification({
            title: '提示',
            message: '加载中，请稍等',
            type: 'warning',
        })
    }
    handlePaymentFlag.value = true
    let consumeCode = ls.get("TABLE_INFO").consumeCode; // 消费单号
    // GetOrderDetail(consumeCode, route.query.state, route.query.payBatchCode)
    let contentData = {
        consumeCode: consumeCode,
        // orderBatchCode: '0004202405130001',
        // state: 1,
        detail: []
    }
    contentData.detail.push(...menuGoodsList.value)
    calculateOrderQty(contentData.detail)
    calculateOrderQtyNew(contentData.detail)
   
    await Api.Common.PcObjProcess.Do({ functionName: "CheckEstmGoodsInfo", contentData })
        .then(res => {
           console.log(res);
           
        })
    // 换菜的价格一样，无需退款或者付款
    if (goodsTotalData.value.totlePrice == 0 || route.query.state == '1') {
        ElMessageBox.confirm('是否确定换菜？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        }
        ).then(() => {
            contentData={...contentData,ip:ip.value};
            Api.Common.PcObjProcess.Do({ functionName: "OpPayBatchChangeGoods", contentData })
                .then(res => {
                    console.log('换菜res :>> ', res);
                    // let itemCodeList = res.newGoods.map(item => {
                    //     return item.itemCode
                    // })
                    ElNotification({
                        title: '提示',
                        message: '换菜成功',
                        type: 'success',
                    })
                    handlePaymentFlag.value = false
                    router.back()
                }).catch(err=>{
                    handlePaymentFlag.value = false
                })
            })
    }
    else if (goodsTotalData.value.totlePrice > 0) {
        router.push({
            path: '/order/payment',
            query: {
                // itemCodeList: itemCodeList.join(','),
                contentData: JSON.stringify(contentData),
                oldItemCode: oldItemCode.join(','),
                price: isVipPay.value ? formatDecimal(goodsTotalData.value.calcVipPrice) : formatDecimal(goodsTotalData.value.totlePrice),
                vipPrice: formatDecimal(goodsTotalData.value.totleVipPrice),
                consumeCode: ls.get("TABLE_INFO").consumeCode,
                roomCode: ls.get("TABLE_INFO").roomCode,
                payBatchCode: route.query.payBatchCode,
                todo: 'orderChange',
                isVip:isVipPay.value ? '1':'0',
                serviceList:JSON.stringify(serviceList.value)
            }
        })
        handlePaymentFlag.value = false
    }
    else if (goodsTotalData.value.totlePrice < 0) {
        console.log(goodsTotalData.value.totlePrice);
        
        let total = 0;
        if(serviceList.value){
            serviceList.value.forEach(item => {
                if (item.type === '抹零' || item.type === '折扣优惠') {
                    total += item.amt; 
                } else if(item.type === '服务费' || item.type === '补低消') {
                    total -= item.amt; 
                }
            });
        }
        router.push({
            path: '/refund',
            query: {
                contentData: JSON.stringify(contentData),
                roomName: OrderDetail.value.roomName,
                returnGoodsPrice: Math.abs(Number(goodsTotalData.value.totlePrice) + total),
                consumeCode: ls.get("TABLE_INFO").consumeCode,
                // roomCode: res.roomCode,
                payBatchCode: route.query.payBatchCode,
                todo: 'orderChange',
                serviceList:JSON.stringify(serviceList.value),
                returnReason:'换菜'

            }
        })
        handlePaymentFlag.value = false
    }

}

// 套餐子项数量调整 不知道干什么的
function calculateOrderQty(items) {
  // 首先按 indexStr 分组
  const groupedItems = {};
  items.forEach(item => {
    if (!groupedItems[item.indexStr]) {
      groupedItems[item.indexStr] = [];
    }
    groupedItems[item.indexStr].push(item);
  });

  // 处理每个分组
  for (const indexStr in groupedItems) {
    const group = groupedItems[indexStr];
    let itemType2OrderQty = null;

    // 找到itemType为2的对象，并记录其orderQty
    group.forEach(item => {
      if (item.itemType == '2') {
        itemType2OrderQty = item.orderQty;
      }
    });

    if (itemType2OrderQty != null) {
      // 计算其它对象的orderQty乘以itemType为2的对象的orderQty
      group.forEach(item => {
        if (item.itemType == '3') {
          item.orderQty = Number(itemType2OrderQty) * Number(item.orderQty);
        }
      });
    }
  }

  return items;
}

//  处理套餐子项的数量
function calculateOrderQtyNew(items) {
    items.forEach(v=>{
        if(v.isNew){
            let toolNum = v.goodsQty
            if(v.subDetail){
                v.subDetail.map(e=>{
                    e.goodsQty = Number(toolNum) * Number(e.goodsQty);
                })
            }
        }
    })
  return items;
}


</script>
<style scoped lang="scss">
* {
    font-size: 16px;
    -webkit-user-select: none;
    /* Safari */
    -moz-user-select: none;
    /* Firefox */
    -ms-user-select: none;
    /* IE/Edge */
    user-select: none;
    /* 标准语法 */
}

.pageClose {
    display: flex;
    justify-content: space-between;
    box-sizing: border-box;
    padding-top: 20px;
    padding-right: 80px;
    padding-left: 80px;
    margin-right: calc(100% - 100vw);
    margin-bottom: 10px;
    div {
        width: 120px;
        padding: 18px 0;
        border-radius: 10px;
        text-align: center;
        font-size: 18px;
        background-color: #CCCCCC;
        cursor: pointer;
    }
    .pageTitle{
        width: 120px;
        height: 24px;
        font-family: Microsoft YaHei;
        font-weight: bold;
        font-size: 24px;
        color: #212121;
        line-height: 24px;
        background-color: rgba(0, 0, 0, 0);

    }
}

.body {
    width: 100%;
    height: 100%;
    background-color: #F2F2F2;
    overflow-x: hidden;
}

.boxContent {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-right: calc(100% - 100vw);
    color: #212121;
    box-sizing: border-box;
    padding: 20px 80px;
    padding-top: 0;
}

.boxLeft {
    display: flex;
    align-items: flex-start;

    .orderBox {
        width: 570px;
        height: 830px;
        background-color: #fff;
        overflow: hidden;
        border-radius: 10px 0px 0px 10px;

        .tableTop {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 15px 20px;
        }

        .orderDetails {
            // height: 375px;
            // overflow-y: auto;
            position: relative;

            .goodsTop {
                margin-left: 10px;
                border-radius: 8px;
                background-color: #E6E6E6;
                padding: 15px 20px;
                display: flex;


                div {
                    text-align: center;
                }
            }





            .goodsList::-webkit-scrollbar {
                      display: none; /* 隐藏滚动条 */
            }
            .goodsList {
                height: 270px;
                scrollbar-width: none; /* 隐藏滚动条 */
                -ms-overflow-style: none; /* 隐藏滚动条 */
                overflow-y: auto;

                .goodsItem {
                    padding: 10px 20px;
                    display: flex;
                    align-items: center;
                    cursor: pointer;

                    div {
                        text-align: center;
                        &.spe{
                            font-size: 14px;
                        }
                    }
                }

                .isNew {
                    color: #FF3333;
                }

                .MenuItemActive {
                    background-color: #FFFBE5;
                }
            }

            .totalAmt {
                padding: 20px;
                font-size: 18px;
                position: absolute;
                left: 0;
                bottom: -55px;
                color: #FF6A00;
            }
        }

        .orderCheckout {
            display: flex;
            align-items: center;
            justify-content: center;
            margin-top: 35px;

            div {
                width: 30%;
                padding: 15px 0;
                border-radius: 10px;
                font-size: 18px;
                text-align: center;
                cursor: pointer;
                margin: 0 12px;
            }
        }
    }

    .menuOperation {
        background-color: #FFF;
        border-radius: 0px 10px 10px 0px;
        padding-top: 108px;
        height: 830px;
        div {
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #FFF6CC;
            font-size: 18px;
            padding: 0 15px;
            height: 60px;
            border-radius: 8px;
            margin: 11px;
            margin-bottom: 20px;

            img {
                width: 32px;
                height: 32px;
                margin-left: 7px;
            }
        }
    }
}

.boxRight {
    width: 1000px;



    .goodsBox {
        width: 100%;
        height: 830px;
        background-color: #FFF;
        box-sizing: border-box;
        padding-top: 20px;
        border-radius: 8px;
        display: flex;
        justify-content: space-between;

        .goodsLeft {
             margin-right: 10px;
            .menuScroll {
                position: relative;
                top: -13px;
                width: 120px;
                border-radius: 10px 0 0px 10px ;
                overflow: hidden;
                background-color:#fff;
                padding-bottom: 12px;
                .goodsMenu-ff {
                    border-radius:8px;
                    padding-left: 10px;
                    padding-right: 10px;
                    // padding: 20px 10px 20px 10px;
                    
                    background-color:#fff;
                }
                .goodsMenu {
                    margin-top: 20px;
                    width: 145px;
                    height: 700px;
                    background-color:#f2f2f2;
                    overflow-y: scroll;
                    overflow-x: hidden;
                    border-radius:8px;
                    .title_box {
                        width: 120px;
                        // padding: 18px 0;
                        height: 57px;
                        // line-height: 57px;
                        font-size: 18px;
                        color: #666666;
                        text-align: center;
                        cursor: pointer;
                        .title-out{
                            width: 80px;
                            height: 57px;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            border-bottom: 1px solid #D9D9D9;
                            margin: 0 25px 0 auto;
                            .title{
                                width: 80px;
                                height: auto;
                                line-height: normal;
                                
                                // vertical-align:middle;
                            }
                        }
                       
                    }

                    .TypeActive {
                        background-color: #ffe566;
                        color: #212121;
                     
                    }
                    .TypeActivebt .title{
                        border-bottom: none;
                    }
                    .TypeActive .title{ 
                        border-bottom: none;
                    }
                    .title_box:nth-last-child(1) .title-out {
                        border-bottom: none;
                    }
                }
                .SearchBtn {
                    width: 110px;
                    margin: 20px 0px auto auto;
                   height: 48px;
                   line-height: 48px;
                    background-color: #FFD400;
                    // margin-top: 20px;
                    border-radius: 10px;
                    font-size: 16px;
                    text-align: center;
                    cursor: pointer;
                }
            }

            .sCodeSearch {
                position: relative;
                margin-left: 10px;
                top: -26px;
                .SearchBtn {
                    width: 110px;
                    padding: 15px 0;
                    background-color: #FFD400;
                    margin-top: 20px;
                    border-radius: 10px;
                    font-size: 18px;
                    text-align: center;
                    cursor: pointer;
                   
                }

                .SearchPanel {
                    background-color: #FFFFFF;
                    position: absolute;
                    right: -605px;
                    bottom: 1px;
                    border-radius: 10px;
                    overflow: hidden;
                    border: 1px solid #FFD400;
                    box-sizing: border-box;
                    padding: 20px;
                    z-index: 99;
                    width: 600px;

                    // height: 610px;
                    .SearchHead {
                        display: flex;
                        align-items: center;
                        justify-content: space-between;

                        .SearchBar {
                            display: flex;
                            align-items: center;
                            border: 1px solid #FFD400;
                            box-sizing: border-box;
                            padding: 1px;
                            border-radius: 30px;
                            height: 48px;

                            div {
                                width: 400px;
                                color: #999999;
                                box-sizing: border-box;
                                padding-left: 20px;
                            }

                            span {
                                font-size: 18px;
                                background-color: #FFD400;
                                border-radius: 30px;
                                width: 82px;
                                height: 44px;
                                line-height: 44px;
                                text-align: center;
                                cursor: pointer;
                            }
                        }

                        img {
                            width: 40px;
                            height: 40px;
                        }
                    }

                    .SearchKey {
                        border: 1px solid #767676;
                        border-radius: 10px;
                        overflow: hidden;
                        display: flex;
                        align-items: center;
                        flex-wrap: wrap;
                        margin-top: 20px;

                        div {
                            width: 10%;
                            height: 55px;
                            line-height: 55px;
                            text-align: center;
                            border: 1px solid #E1E1E1;
                            color: #161616;
                            font-size: 17px;
                            cursor: pointer;
                        }

                        div:last-child {
                            width: 20%;
                        }
                    }
                }
            }
        }

        .goodsRight {
            // width: 862px;
            // margin-right: 18px;
            // display: flex;
            // // align-items: center;
            // justify-content: space-between;
            // flex-wrap: wrap;
            width: 1015px;
            height: 800px;
            padding: 10px 10px 10px;
            display: flex;
            align-content: flex-start; /* 换行后对齐到容器的起始位置 */
            // flex-direction: column;
            // align-items: center;
            // justify-content: space-between;
            gap: 6px;
            flex-wrap: wrap;
            background: #fff;
            border-radius:8px ;
            .goodsRight-item{
                height: 250px;
            }
            .goodsItem {
                background-color: #F2F2F2;
                border-radius: 10px;
                box-sizing: border-box;
                padding: 10px 10px 20px 10px;
                margin-bottom: 11px;
                position: relative;
                cursor: pointer;
                .Mask {
                    width: 100%;
                    height: 100%;
                    border-radius: 10px;
                    position: absolute;
                    background-color: rgba(0, 0, 0, 0.6);
                    left: 0;
                    top: 0;
                    z-index: 99;

                    div {
                        position: absolute;
                        left: 0;
                        right: 0;
                        top: 0;
                        bottom: 0;
                        margin: auto;
                        width: 100%;
                        height: 50px;
                        line-height: 50px;
                        color: #fff;
                        font-size: 24px;
                        text-align: center;
                        margin: auto;
                    }
                }

                .goodsLogoS {
                    position: relative;
                    border-radius: 5px;
                    // overflow: hidden;
                    margin-bottom: 4px;
                    .img-jinbi{
                        position: absolute;
                        width: 40px;
                        height: 20px;
                        right: -10px;
                        top: -10px;
                    }

                    .goodsLogo {
                        width: 140px;
                        height: 140px;
                        vertical-align: middle;
                    }

                    .goodsVipPrice {
                        width: 100%;
                        position: absolute;
                        bottom: 0;
                        left: 0;
                        background-color: rgba($color: #000000, $alpha: 0.5);
                        color: #fff;
                        font-size: 12px;
                        text-align: center;
                        padding: 2px 0;
                    }
                }

                .goodsName {
                    width: 140px;
                    height: 44px;
                    display: -webkit-box;
                    -webkit-box-orient: vertical;
                    -webkit-line-clamp: 2;
                    overflow: hidden;
                    line-height: 1.4;

                    span {
                        color: #fff;
                        background-color: #FF3333;
                        font-size: 14px;
                        padding: 0 4px;
                        border-radius: 5px;
                        margin-right: 5px;
                    }
                }

                .goodsPrice {
                    color: #FF3333;
                    font-size: 18px;
                }

                .coin {
                    position: absolute;
                    right: 5px;
                    top: 5px;
                    background-color: #FF6A00;
                    color: #fff;
                    font-size: 14px;
                    border-radius: 30px;
                    letter-spacing: 1px;
                    padding: 1px 5px;
                }
            }

            .holde {
                background-color: transparent;
                width: 160px;
                padding: 0;
                margin: 0;
            }



                .goodsPage {
                    display: grid;
                    height: 116px;
                    grid-template-columns: auto;
                    // grid-column-gap: 40px;
                    grid-row-gap: 10px;
                    margin-bottom: 11px;
                div {
                    width: 160px;
                    height: 116px;
                    border-radius: 10px;
                    text-align: center;
                    padding: 39px 0px;
                    background-color: #F2F2F2;
                    font-size: 22px;
                    cursor: pointer;
                }

                .disbPages {
                    pointer-events: none;
                    background: #F2F2F2 !important;
                    color: #ccc !important;
                    cursor: not-allowed;
                    // opacity: 0;
                }
            }
        }
    }
}

::v-deep(.menuDialog) {
    padding: 0;
    margin: 0;
    top: 190px;
    left: 620px;
    border-radius: 15px;
    overflow: hidden;
    border: 1px solid #FFD400;

    .el-dialog__header {
        background-color: #FFD400;
        padding: 16px 0;

        .el-dialog__title {
            font-size: 19px;
            font-weight: bold;
        }
    }
}
::v-deep(.FlavorDialog) {
    .modFlavor {
        display: flex;
        align-items: center;
        margin-top: 15px;

        div {
            cursor: pointer;
            background-color: rgb(230, 230, 230);
            padding: 3px 10px;
            border-radius: 5px;
            margin-right: 10px;
        }

        .isActs {
            background-color: #FFE566;
        }
    }

    .setPrices {
        background-color: #FFE566 !important;
        color: #212121 !important;
    }

    .btnS {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 20px;

        .btn {
            width: 45%;
            text-align: center;
            border-radius: 10px;
            border: 1px solid #FF6A00;
            color: #FF6A00;
            padding: 10px 0;
        }

        .btn:hover {
            background-color: #FF6A00;
            color: #fff;
            cursor: pointer;
        }
    }
}
.digitalPanel {
    box-sizing: border-box;
    padding: 30px 20px;
    padding-bottom: 0;

    ::v-deep(.el-input) {
        height: 50px;
        margin-bottom: 30px;

        .el-input__wrapper {
            background-color: #F9F9F9;
            font-size: 18px;
        }

    }

    .digitalNum {
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex-wrap: wrap;

        .numBtn {
            width: 80px;
            height: 80px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #212121;
            font-size: 22px;
            background-color: #E6E6E6;
            margin-bottom: 20px;
            border-radius: 10px;
            cursor: pointer;
        }

        .numBtn:hover {
            background-color: #FF6A00;
            color: #fff;
        }
    }
}

.dialog-footer {
    display: block;
    padding-bottom: 30px;

    .el-button {
        width: 160px;
        height: 60px;
        font-size: 26px;
        border-color: #FF6A00;
        color: #FF6A00;
        border-radius: 10px;
    }

    .el-button:hover {
        background-color: #FF6A00;
        color: #fff;
    }

    .el-button+.el-button {
        margin-left: 30px;
    }
}

.tasteContent {
    box-sizing: border-box;
    padding: 20px;
    padding-bottom: 0;
    display: flex;
    align-items: flex-start;
    height: 450px;

    .tasteClass {
        width: 15%;
        height: 100%;
        background-color: #FAFAFA;
        border-radius: 10px;
        overflow: hidden;

        div {
            text-align: center;
            font-size: 18px;
            color: #666;
            padding: 19px 0;
            cursor: pointer;
        }

        .FlavorActive {
            background-color: #FFE566;
            color: #212121;
        }
    }

    .tasteList {
        width: 85%;
        display: grid;
        box-sizing: border-box;
        padding-left: 20px;
        grid-template-columns: repeat(4, 23%);
        justify-content: space-between;
        grid-gap: 20px 0;

        .tasteItem {
            background-color: #E6E6E6;
            border-radius: 10px;
            text-align: center;
            font-size: 20px;
            padding: 19px 0;
            cursor: pointer;
        }

        .tasteActive {
            background-color: #FFE566;
            color: #212121;
        }
    }
}

.remarkContent {
    box-sizing: border-box;
    padding: 18px;
    position: relative;

    textarea {
        font-size: 18px;
        resize: none;
        width: 100%;
        background-color: #FAFAFA;
        box-sizing: border-box;
        padding: 18px 20px;
    }

    div {
        position: absolute;
        right: 30px;
        bottom: 30px;
        color: #00AAFF;
        cursor: pointer;
    }
}

</style>